package com.study.talk.ui.app.common

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.study.talk.R
import com.study.talk.ai.AiModel
import com.study.talk.databinding.FragmentAnalyzeImageBinding
import com.study.talk.ui.adapter.AnalyzePictureListAdapter
import com.study.talk.utils.extras.showToast
import com.study.talk.utils.extras.take
import com.study.talk.utils.extras.useless
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole


class AnalyzeImageFragment(private val contexts : MutableList<ChatMessage>) : DialogFragment() {

    private val adapter by lazy { AnalyzePictureListAdapter(contexts) }

    private lateinit var bing: FragmentAnalyzeImageBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.TransparentDialog)
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT
        )
        dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        bing = FragmentAnalyzeImageBinding.inflate(layoutInflater, container, false)
        sendMsg()
        return bing.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        bing.smartChatList.layoutManager = LinearLayoutManager(context)
        bing.smartChatList.adapter = adapter
        adapter.notifyItemInserted(contexts.lastIndex)
        bing.smartChatMsgSendBt.setOnClickListener {
            if (bing.smartChatMsgEdit.useless("请输入问题")) return@setOnClickListener
            contexts.add(buildContentMsg(bing.smartChatMsgEdit.take()))
            adapter.notifyItemInserted(contexts.lastIndex)
            sendMsg()
        }
        super.onViewCreated(view, savedInstanceState)
    }

    private fun buildContentMsg(content: String): ChatMessage {
        return ChatMessage.builder().role(ChatMessageRole.USER).content(content).build()
    }

    private fun buildSystemMsg(content: String): ChatMessage {
        return ChatMessage.builder().role(ChatMessageRole.SYSTEM).content(content).build()
    }

    private fun sendMsg() {
        AiModel.analyzeImage(msg = contexts, start = {
            contexts.add(buildSystemMsg("加载中..."))
        }, subscribe = {
            contexts[contexts.lastIndex].content = it
            adapter.notifyItemChanged(contexts.lastIndex, "contentUpdating")
        }, finish = {}, error = {
            showToast("访问出错!")
        })
    }
}